extends PanelContainer

@onready var round_label = $VBoxContainer/RoundLabel
@onready var phase_label = $VBoxContainer/PhaseLabel
@onready var timer_label = $VBoxContainer/TimerLabel

var round_manager

func _ready():
	print("RoundInfoUI ready")
	
	# Wait for scene to be ready
	await get_tree().process_frame
	
	# Find RoundManager with multiple fallbacks
	round_manager = get_node_or_null("/root/Main/RoundManager")
	if not round_manager:
		round_manager = get_node_or_null("../../RoundManager")
	
	if round_manager:
		print("RoundInfoUI: Found RoundManager at ", round_manager.get_path())
		
		# Connect all signals
		if round_manager.has_signal("round_started"):
			round_manager.round_started.connect(_on_round_started)
			print("Connected to round_started signal")
		
		if round_manager.has_signal("phase_changed"):
			round_manager.phase_changed.connect(_on_phase_changed)
			print("Connected to phase_changed signal")
		
		if round_manager.has_signal("preparation_time_updated"):
			round_manager.preparation_time_updated.connect(_on_timer_updated)
			print("Connected to preparation_time_updated signal")
		
		# Set initial values
		_on_round_started(1)
		_on_phase_changed(0)  # 0 = PREPARATION
		_on_timer_updated(30.0)
	else:
		print("WARNING: RoundInfoUI could not find RoundManager!")
		
		# Set default text if no manager found
		if round_label:
			round_label.text = "Round 1"
		if phase_label:
			phase_label.text = "Preparation Phase"
		if timer_label:
			timer_label.text = "30s"

func _on_round_started(round_number: int):
	print("RoundInfoUI: Round started - ", round_number)
	if round_label:
		round_label.text = "Round " + str(round_number)
	else:
		print("WARNING: round_label is null!")

func _on_phase_changed(phase):
	print("RoundInfoUI: Phase changed - ", phase)
	if phase_label:
		var phase_text = "Preparation Phase" if phase == 0 else "Battle Phase"
		phase_label.text = phase_text
	else:
		print("WARNING: phase_label is null!")

func _on_timer_updated(time_left: float):
	# Only update if timer_label exists
	if timer_label:
		var seconds = int(ceil(time_left))  # Round up for better UX
		timer_label.text = str(max(0, seconds)) + "s"
		
		# Change color based on time remaining
		if seconds <= 5:
			timer_label.modulate = Color(1, 0.3, 0.3)  # Red when low
		elif seconds <= 10:
			timer_label.modulate = Color(1, 1, 0.3)  # Yellow when medium
		else:
			timer_label.modulate = Color(1, 1, 1)  # White normally